package com.haoshuang.zhouzhoubang.utils

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.net.Uri
import android.util.Log
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.text.SimpleDateFormat
import java.util.Date

object UploadSignUtil {


    private var creatTime: String? = null
    public var signatureFile: File? = null
    private var mContext: Context? = null

    fun requestPermission(context: Context, signatureBitmap: Bitmap){
        mContext = context

        val baos = ByteArrayOutputStream()
        signatureBitmap.compress(
            Bitmap.CompressFormat.PNG,
            100,
            baos
        )
        //var saveBitmap = compressScale(signatureBitmap)
        var isSave = addSignatureToGallery(signatureBitmap)
    }

    fun addSignatureToGallery(signature: Bitmap?): Boolean {
        val formatter = SimpleDateFormat("yyyyMMddhhmmss")
        val curDate = Date(System.currentTimeMillis()) //获取当前时间
        creatTime = formatter.format(curDate)
        var result = false
        try {
            signatureFile = File(
                getAlbumStorageDir("QTdraw"),
                String.format(creatTime + ".jpg", System.currentTimeMillis())
            )
            saveBitmapToJPG(signature!!, signatureFile)
            val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
            val contentUri = Uri.fromFile(signatureFile)
            mediaScanIntent.data = contentUri
            mContext?.sendBroadcast(mediaScanIntent)
            result = true
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return result
    }

    @Throws(IOException::class)
    fun saveBitmapToJPG(bitmap: Bitmap, photo: File?) {
        val newBitmap = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(newBitmap)
        canvas.drawColor(Color.WHITE)
        canvas.drawBitmap(bitmap, 0f, 0f, null)
        val stream: OutputStream = FileOutputStream(photo)
        newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream)
        stream.close()
    }

    fun getAlbumStorageDir(albumName: String?): File? {
        val file = File(mContext?.getExternalFilesDir(""), albumName)
        if(!file.exists()){
            file.mkdirs()
        }
        if (!file.mkdirs()) {
            Log.e("SignaturePad", "Directory not created")
        }
        return file
    }

}